//
//  MNDLoginViewController.m
//  minidai
//
//  Created by Steven.Yung on 2017/5/4.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDLoginViewController.h"
#import "MNDRegisterViewController.h"
#import "MNDForgotViewController.h"
#import "MNDLoginModel.h"
#import "MNDLoginUserModel.h"
#import "RSAUtil.h"
#import <UMPush/UMessage.h>
#import "UIButton+JKImagePosition.h"
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import "MNDBindWechatTableViewController.h"
#import <ShareSDKExtension/ShareSDK+Extension.h>
#define  kCheckMyMessageNotificationName @"CheckMyMessageNotificationName"

@interface MNDLoginViewController () <UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UITextField *tfUsername;
@property (weak, nonatomic) IBOutlet UITextField *tfPassword;
@property (nonatomic, strong) MNDLoginModel *loginModel;
@property (weak, nonatomic) IBOutlet UIView *shadowView;
//之前是否保存过此用户名
@property(nonatomic, assign) BOOL isSaveAccount;
@property (weak, nonatomic) IBOutlet UILabel *userNameTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *passwordTipLabel;
@property (weak, nonatomic) IBOutlet UIView *userNameView;
@property (weak, nonatomic) IBOutlet UIView *passwordView;
@property (weak, nonatomic) IBOutlet UIButton *wechatButton;
@property (weak, nonatomic) IBOutlet UIImageView *wechatImgView;
@property (weak, nonatomic) IBOutlet UILabel *wechatLabel;
@property (weak, nonatomic) IBOutlet UIView *wechatLeftLineView;
@property (weak, nonatomic) IBOutlet UILabel *thirdTipLabel;
@property (weak, nonatomic) IBOutlet UIView *wechatRightLineView;

@end

@implementation MNDLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.naviBarTranslucent = YES;
    
    self.shadowView.layer.cornerRadius = 4.0;
    self.shadowView.layer.shadowOpacity = 0.4;
    self.shadowView.layer.shadowOffset = CGSizeMake(2.0, 2.0);
    self.shadowView.layer.shadowRadius = 4.0;
    self.shadowView.layer.shadowColor = kColorOrange.CGColor;
    
    self.tfUsername.delegate = self;
    self.tfPassword.delegate = self;
    
    [self setupUI];
    
    [self initialLeftBarButtons];
    
    //判断是否安装微信，未安装则隐藏微信登录
    if (![ShareSDK isClientInstalled:SSDKPlatformTypeWechat]) {
        self.wechatButton.hidden = YES;
        self.wechatImgView.hidden = YES;
        self.wechatLabel.hidden = YES;
        self.wechatLeftLineView.hidden = YES;
        self.wechatRightLineView.hidden = YES;
        self.thirdTipLabel.hidden = YES;
    }
}

- (void)setupUI {
    __weak __typeof(self)weakSelf = self;
    [self.tfUsername bk_addEventHandler:^(id sender) {
        if (weakSelf.tfUsername.text.length > 0) {
            weakSelf.userNameTipLabel.hidden = NO;
            weakSelf.userNameTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.userNameTipLabel.hidden = YES;
        }
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.tfUsername bk_addEventHandler:^(id sender) {
        weakSelf.userNameView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidBegin];
    
    [self.tfUsername bk_addEventHandler:^(id sender) {
        
        if(weakSelf.tfUsername.text.length <= 0) {
            weakSelf.userNameTipLabel.hidden = YES;
        }
        weakSelf.userNameTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.userNameView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1.0];
        
    } forControlEvents:UIControlEventEditingDidEnd];
    
    [self.tfPassword bk_addEventHandler:^(id sender) {
        if (weakSelf.tfPassword.text.length > 0) {
            weakSelf.passwordTipLabel.hidden = NO;
            weakSelf.passwordTipLabel.textColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
        }else {
            weakSelf.passwordTipLabel.hidden = YES;
        }
    } forControlEvents:UIControlEventEditingChanged];
    
    [self.tfPassword bk_addEventHandler:^(id sender) {
            weakSelf.passwordView.backgroundColor = [UIColor colorWithRed:255/255.0 green:110/255.0 blue:63/255.0 alpha:1.0];
    } forControlEvents:UIControlEventEditingDidBegin];
    
    [self.tfPassword bk_addEventHandler:^(id sender) {
        
        if(weakSelf.tfPassword.text.length <= 0) {
            weakSelf.passwordTipLabel.hidden = YES;
        }
        weakSelf.passwordTipLabel.textColor = [UIColor colorWithRed:203/255.0 green:203/255.0 blue:203/255.0 alpha:1.0];
        weakSelf.passwordView.backgroundColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:1.0];
        
    } forControlEvents:UIControlEventEditingDidEnd];
    
    [self.wechatButton jk_setImagePosition:LXMImagePositionTop spacing:4.0];
    
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    
//    textField.placeholder = @"";
    
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
//    if (textField == self.tfUsername) {
//        textField.placeholder = @"请输入手机号/用户名";
//    }
//    
//    if (textField == self.tfPassword) {
//        textField.placeholder = @"请输入密码";
//    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
}

- (void)initialLeftBarButtons {
    UIImage *backImage = [UIImage imageNamed:@"login_dismiss_btn"];
    
    //创建返回按钮
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:backImage
                                                                          style:UIBarButtonItemStylePlain
                                                                         target:self
                                                                         action:@selector(dismissLoginAction:)];
    //设置返回按钮的颜色
    [backBarButtonItem setTintColor:kColorBackButtonColor];
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    //将两个BarButtonItem都返回给NavigationItem
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = backBarButtonItem;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, backBarButtonItem];
    }
}

#pragma mark - Action
- (IBAction)dismissLoginAction:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_state" object:@(NO)];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)loginAction:(id)sender {
    
    [self.view endEditing:YES];
    
    self.loginModel = [MNDLoginModel new];
    self.loginModel.userName = self.tfUsername.text;
    self.loginModel.userLoginPassword = self.tfPassword.text;
    if (self.loginModel.userName.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入用户名或手机号"];
        return;
    }
    
    if (self.loginModel.userLoginPassword.length <= 0) {
        [NetworkProgressHUD showHudMsg:@"请输入密码"];
        return;
    }
    
    [self loginWithUser:self.loginModel];
}

- (IBAction)wechatLoginAction:(UIButton *)sender {
    [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeWechat
                                   onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                       NSLog(@"user = %@",user);
                                       //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
                                       //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
                                       [NetworkProgressHUD showHud];
                                       if (user.uid.length <= 0) {
                                           user.uid = @"";
                                       }
                                       if (user.nickname.length <= 0) {
                                           user.nickname = @"";
                                       }
                                       if (user.icon.length <= 0) {
                                           user.icon = @"";
                                       }
                                       
                                       
                                       NSDictionary *params = @{
                                                                @"unionid":user.credential.rawData[@"unionid"],
                                                                @"open_id": user.credential.rawData[@"openid"],
                                                                @"open_name": user.nickname,
                                                                @"open_img": user.icon,
                                                                @"open_sex": user.gender == 0 ? @(-1):@(1),
                                                                @"open_type": @"1",
                                                                @"source": @"app"
                                                                };
                                       kdeclare_weakself;
                                    
                                       //开始登录
                                       [APIManager sendRequestWithURL:API_WECHAT_LOGIN parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
                                           [NetworkProgressHUD hideHud];
//                                           [NetworkProgressHUD showHudMsg:responseModel.msg[@"success"]];
                                           if (responseModel.status == ResponseSuccess) {
                                               NSString *str = responseModel.data[@"is_bind"];
                                               
                                               if (str.integerValue == -1) {//未绑定
                                                   
                                                   [weakSelf goBindWechat:(SSDKUser *)user];
                                               }else {//已绑定
                                                   //登录
                                                   MNDLoginUserModel *userModel = [MNDLoginUserModel mj_objectWithKeyValues:responseModel.data];
                                                   //更新数据库
                                                   [MNDLoginUserModel addOrUpdateUser:userModel];
                                                   //设置用户标识
                                                   [Bugly setUserIdentifier:userModel.user_id];
                                                   
                                                   [weakSelf setHTTPHeaders];
    
                                                   //设置消息推送别名
                                                   [UMessage setAlias:userModel.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                                                       if (error) {
                                                           NSLog(@"设置别名失败: %@", error);
                                                       } else {
                                                           NSLog(@"设置别名成功: %@", responseObj);
                                                       }
                                                   }];
                                                   [self dismissViewControllerAnimated:YES completion:nil];
                                               }
                                               NSLog(@"responseModel = %@",responseModel);
                                           }else {
                                               [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                                           }
                                       } onFailure:^(NSError *error) {
                                           [NetworkProgressHUD showHudNetworkError:error];
                                       }];
                                       associateHandler (user.uid, user, user);
                                       NSLog(@"dd%@",user.rawData);
                                       NSLog(@"dd%@",user.credential);
                                       
                                   }
                                onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                    
                                    if (state == SSDKResponseStateSuccess)
                                    {
                                       
                                    }
                                    
                                }];
}

//绑定微信
- (void)goBindWechat:(SSDKUser *)user {
    MNDBindWechatTableViewController *bindVC = [UIStoryboard viewControllerWithIdentifier:@"MNDBindWechatTableViewController"];
    bindVC.user = user;
    [self.navigationController pushViewController:bindVC animated:YES];
}

- (IBAction)toRegisterAction:(id)sender {
    
    [self performSegueWithIdentifier:[MNDRegisterViewController description] sender:nil];
}

- (IBAction)toForgotPasswordAction:(id)sender {
    
    [self performSegueWithIdentifier:[MNDForgotViewController description] sender:nil];
}

- (IBAction)showOrHidePasswordAction:(UIButton *)sender {
    
    sender.selected = !sender.isSelected;
    
    if (sender.isSelected) {
        [self.tfPassword setSecureTextEntry:NO];
    } else {
        [self.tfPassword setSecureTextEntry:YES];
    }
}

#pragma mark - Network

- (void)loginWithUser:(MNDLoginModel *)userModel {
    
    __weak typeof(self) weakSelf = self;
    
    NSDictionary *params = [userModel mj_JSONObject];
    NSLog(@"pp: %@", params);
    [NetworkProgressHUD showHud];
    
    [APIManager sendRequestWithPath:API_USER_LOGIN parameters:[MNDSign signedParamWithDict:userModel.mj_JSONObject] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        
        if (responseModel.status == ResponseSuccess) {
            [NetworkProgressHUD showHudMsg:@"登录成功"];
            [UserDefaultsTool removeForKey:kForgetGesture];
            MNDLoginUserModel *user = [MNDLoginUserModel mj_objectWithKeyValues:responseModel.data];
            if (weakSelf.isAddAccount) {//切换账号，先退出之前账号
                [weakSelf loginOutAction:user];
            }else {
                //保存数据库
                [MNDLoginUserModel addOrUpdateUser:user];
                //保存用户名用于账号管理切换账号
                NSArray *array = [UserDefaultsTool objectForKey:kAccountUserNameArray];
                for (NSDictionary *dict in array) {
                    if ([dict[@"user_name"] isEqualToString:user.user_name]) {
                        weakSelf.isSaveAccount = YES;
                    }
                }
                [weakSelf saveUserNameFromArray:array user:user];
                //            [UserDefaultsTool saveObject:responseObject.data forKey:kCurrentUser];
                
                //设置用户标识
                [Bugly setUserIdentifier:user.user_id];
                
                [weakSelf setHTTPHeaders];
                if (self.isCheckMyMessage) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:kCheckMyMessageNotificationName object:nil];
                }
                
                //设置消息推送别名
                [UMessage setAlias:user.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                    if (error) {
                        NSLog(@"设置别名失败: %@", error);
                    } else {
                        NSLog(@"设置别名成功: %@", responseObj);
                    }
                }];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    NSLog(@"login user: %@", user.description);
                    [weakSelf setHTTPHeaders];
                    [weakSelf dismissLogin];
                });
            }
            
        } else {
            NSDictionary *dic = responseModel.msg;
            [NetworkProgressHUD showHudMsg:dic[@"error"]];
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)setHTTPHeaders {
    //传userCode
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    if (user.user_code.length > 0) {
        NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", user.user_code] publicKey:RSA_PUBLIC_KEY];
        NSString *unreserved = @"";
        NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
        [allowed addCharactersInString:unreserved];
        
        NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
        [APIManager setGeneralHeaderValue:encodeEncryText forField:@"USERCODE"];
    }
}


- (void)dismissLogin {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_state" object:@(YES)];
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)dismissLoginAndPop {
    [[NSNotificationCenter defaultCenter] postNotificationName:@"login_state" object:@(YES)];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"AddAccountPopToroot" object:nil];
    [self dismissViewControllerAnimated:YES completion:^{
    
    }];
}

- (void)saveUserNameFromArray:(NSArray *)array user:(MNDLoginUserModel *)user {
    if (_isSaveAccount == NO) {
        NSMutableArray *arrayM = [NSMutableArray arrayWithArray:array];
        
        NSDictionary *dict = @{
                               @"user_name": user.user_name.length > 0 ? user.user_name : @"",
                               @"user_photo":user.user_photo.length > 0 ? user.user_photo : @"",
                               @"user_phone":user.user_phone.length > 0 ? user.user_phone : @""
                               };
        [arrayM addObject:dict];
        [UserDefaultsTool saveObject:[arrayM copy] forKey:kAccountUserNameArray];
        _isSaveAccount = NO;
    }
}

- (void)loginOutAction:(MNDLoginUserModel *)user {
    
    __weak __typeof(self)weakSelf = self;
    [APIManager sendRequestWithPath:API_USER_LOGOUT parameters:[MNDSign signedParam] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
        if (responseModel.status == ResponseSuccess) {
            [UserDefaultsTool removeForKey:kForgetGesture];
            //            [NetworkProgressHUD hideHud];
            [weakSelf clearUserContents];
            
            //保存数据库
            [MNDLoginUserModel addOrUpdateUser:user];
            //保存用户名用于账号管理切换账号
            NSArray *array = [UserDefaultsTool objectForKey:kAccountUserNameArray];
            for (NSDictionary *dict in array) {
                if ([dict[@"user_phone"] isEqualToString:user.user_phone]) {
                    weakSelf.isSaveAccount = YES;
                }
            }
            [weakSelf saveUserNameFromArray:array user:user];
            
            //设置用户标识
            [Bugly setUserIdentifier:user.user_id];
            [weakSelf setHTTPHeaders];
            
            //设置消息推送别名
            [UMessage setAlias:user.user_code type:@"minidai" response:^(id  _Nonnull responseObj, NSError * _Nonnull error) {
                if (error) {
                    NSLog(@"设置别名失败: %@", error);
                } else {
                    NSLog(@"设置别名成功: %@", responseObj);
                }
            }];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                NSLog(@"login user: %@", user.description);
                [weakSelf setHTTPHeaders];
                [weakSelf dismissLoginAndPop];
            });
            
        } else {
            NSDictionary *dict = responseModel.msg;
            if (dict && dict.count > 0) {
                [NetworkProgressHUD showHudMsg:dict[@"error"]];
            } else {
                [NetworkProgressHUD showHudMsg:@"退出失败，请重试"];
            }
        }
    } onFailure:^(NSError *error) {
        [NetworkProgressHUD showHudNetworkError:error];
    }];
}

- (void)clearUserContents {
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    //删除消息推送设置的别名
    [UMessage removeAlias: user.user_code type:@"minidai" response:^(id  _Nonnull responseObject, NSError * _Nonnull error) {
        if (error) {
            NSLog(@"删除别名失败: %@", error);
        } else {
            NSLog(@"删除别名成功: %@", responseObject);
        }
    }];
    //清除用户数据
    
    [MNDLoginUserModel deleteAllUserDatas];
    [UserDefaultsTool removeForKey:kOpenDepositAlert];
    //清空手势密码
    [UserDefaultsTool removeForKey:kGesturePassword];
    //清空手势错误次数
    [UserDefaultsTool removeForKey:kErrorCount];
    //关闭手势密码
    [UserDefaultsTool removeForKey:kFingerPassword];
    //    [[NSNotificationCenter defaultCenter] postNotificationName:@"clearPomeCircleData" object:nil];
    [APIManager setGeneralHeaderValue:nil forField:@"USERCODE"];
    
    [self clearWebViewCookies];
    [self.navigationController popToRootViewControllerAnimated:YES];
}

- (void)clearWebViewCookies {
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
    //缓存web清除
    //    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}
#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:[MNDRegisterViewController description]]) {
        MNDRegisterViewController *registerVC = segue.destinationViewController;
        
        registerVC.isNaviRootVC = NO;
    }
}


@end
